<template>
  <!-- 证件 -->
  <div>
    <el-form ref="form" class="form" :model="query" label-position="right" label-width="80px">
      <el-form-item label="证件类型:" prop="cardType">
        <el-select v-model="query.cardType" placeholder="请选择">
          <el-option
            v-for="(item,index) in cardTypeMap"
            :key="index"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="证件编号:" prop="cardNo">
        <el-input v-model.trim="query.cardNo" placeholder="" clearable>
          <el-button slot="append" class="append-search" @click="getCode">获取</el-button>
        </el-input>
      </el-form-item>
      <el-form-item label-width="10px">
        <el-button type="primary" @click="addMessage">添加</el-button>
      </el-form-item>
      <el-form-item label="备注:" prop="remark" class="block">
        <el-input v-model.trim="query.remark" maxlength="50" />
      </el-form-item>
      <div v-if="imgdata.length" class="info-box">
        <div v-for="(data,index) in imgdata" :key="index" class="info-item">
          <div class="flex">
            <div class="titlename"><span v-if="data.cardType !==3 ">{{ data.cardType && formatColumnMap(cardTypeMap, 'value', data.cardType, 'desc') }}</span><span v-if="data.cardType===3">身份证</span>:<span class="card-no">{{ data.cardNo }}</span></div>
            <div><el-link v-if="data.cardType!==3" type="danger" :underline="false" @click="del(row,index)">删除</el-link></div>
          </div>
          <div>
            <el-button type="primary" @click="pcUpload(data)"> 电脑上传 </el-button>
            <el-button type="primary" @click="phoneUpload(data)"> 手机上传 </el-button>
          </div>
          <div class="img-box">
            <template v-if="data.picInfos && data.picInfos.length">
              <div v-for="(item,j) in data.picInfos" :key="j" class="img-item">
                <img :src="imgBaseUrl+item.url" alt="" @click="scanImg(item)">
                <div class="deleteimg" @click="deleteImg(data,item)"><i class="el-icon-circle-close" /></div>
              </div>
            </template>
            <template v-if=" !data.picInfos || (data.picInfos &&(3- data.picInfos.length)>0)">
              <div v-for="(item,k) in imgList.slice(0,3 - Number((data.picInfos && data.picInfos.length) || 0))" :key="k+Math.random" class="img-item img-empty"><img :src="item.img" alt=""></div>
            </template>
          </div>
          <div v-if="data.remark" class="remark-part">
            备注：{{ data.remark }}
          </div>
        </div>
      </div>
    </el-form>
    <!-- <cert-detail ref="certDetail" /> -->
    <pc-upload ref="pcUpload" />
    <phone-upload ref="phoneUpload" @setUpload="setUpload" />
  </div>
</template>

<script>
  import { queryCodeGeneration, customerAttachment, customerattachmentDelete, customerUpdate } from '@/api'
  import { formatColumnMap } from '@/utils'
  import { imgBaseUrl } from '@/utils/config'
  import PcUpload from '@/views/components/uploadID/PcUpload'
  import PhoneUpload from '@/views/components/uploadID/PhoneUpload'
  import { accSub } from '@/utils/math'
  export default {
    name: 'idInformation',
    components: {
      PcUpload,
      PhoneUpload
    },
    props: {
      cardTypeMap: {
        type: Array,
        required: true
      },
      temp: {
        type: Object,
        required: true
      }
    },
    data() {
      return {
        curSize: 0, // 当前添加的项目个数
        accSub: accSub,
        checkInterval: null,
        imgBaseUrl: imgBaseUrl,
        formatColumnMap: formatColumnMap,
        imgdata: [],
        imgList: [{
          num: 1, type: 'empty', img: require('@/assets/404_images/not_upload.png')
        }, {
          num: 2, type: 'empty', img: require('@/assets/404_images/not_upload.png')
        }, {
          num: 3, type: 'empty', img: require('@/assets/404_images/not_upload.png')
        }],
        query: {
          cardType: '',
          cardNo: '',
          remark: ''
        }
      }
    },
    watch: {
      temp: {
        handler() {
          if (this.temp.cardItems) {
            //  this.imgdata = JSON.parse(JSON.stringify(this.temp.cardItems))
            this.getattachmentlist()
          }
        },
        deep: true
      }
    },
    // mounted() {
    //   this.imgdata = JSON.parse(JSON.stringify(this.temp.cardItems))
    // },
    methods: {
      // 获取编码
      async getCode() {
        const code = {
          codeType: 18
        }
        const res = await queryCodeGeneration(code)
        this.query.cardNo = res.data
      },
      async getattachmentlist(flag) {
        const res = await customerAttachment({ csmCode: this.temp.csmCode })
        this.imgdata = [].concat(res.data.cardItems)

        if (this.temp.sfzh && this.imgdata.length > 0) {
          let addFlag = false
          this.imgdata.forEach(item => {
            if (item.cardType === 3) {
              addFlag = true
            }
          })
          if (!addFlag) {
            this.imgdata.push({
              cardNo: this.temp.sfzh,
              csmId: this.temp.csmId,
              cardType: 3,
              sfzh: this.temp.sfzh
            })
          }
        }

        if (flag) {
          this.$emit('getCardItems', this.imgdata)
        }
        console.log(this.imgdata)
      },
      del(row, index) {
        this.$confirm('确认要删除吗？', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.imgdata.splice(index, 1)
          this.$emit('getCardItems', this.imgdata)
          this.$message({
            type: 'success',
            message: '成功!'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      // 电脑上传
      async pcUpload(data) {
        await this.$refs.pcUpload.open(3 - (data.picInfos && data.picInfos.length || 0), data)
        this.getattachmentlist(1)
      },
      // 手机上传
      async phoneUpload(data) {
        await this.$refs.phoneUpload.open(data)
        this.getattachmentlist()
      },
      deleteImg(data, item) {
        //
        this.$confirm('确认要删除吗？', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await customerattachmentDelete({
            csmId: data.csmId,
            cardType: data.cardType,
            cardNo: data.cardNo,
            picId: item.id
          })
          this.$message({
            type: 'success',
            message: '成功!'
          })
          this.getattachmentlist()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      scanImg(item) {
        window.open(this.imgBaseUrl + item.url, '_blank')
      },
      // 添加信息
      async addMessage() {
        if (!this.query.cardType) {
          this.$message.warning('请选择证件类型')
          return
        }
        if (!this.query.cardNo) {
          this.$message.warning('请输入证件编号')
          return
        }
        if (this.imgdata.length >= 10) {
          this.$message.error('最多只能添加10个证件')
          return
        }
        for (let i = 0; i < this.imgdata.length; i++) {
          if (this.imgdata[i].cardType === this.query.cardType && this.imgdata[i].cardNo === this.query.cardNo) {
            this.$message.error('证件已存在')
            return
          }
        }
        const arr = [].concat(this.imgdata)
        arr.push({ ...this.query, cardStatus: 1 })
        const obj = {}
        this.$set(this.temp, 'cardItems', arr)
        Object.assign(obj, this.temp)
        const res = await customerUpdate(obj)
        if (res.success) {
          this.getattachmentlist(1)
          this.query = {
            cardType: '',
            cardNo: '',
            remark: ''
          }
        }
      },
      setUpload(id) {
        const list = this.imgdata.filter(item => item.csmId === id)
        if (list && list.length) {
          this.curSize = list[0].picInfos && list[0].picInfos.length
          this.checkingPay(id)
        }
      },
      // 轮询查看是否上传成功更新图片
      checkingPay(id) {
        const _this = this
        this.checkInterval = setInterval(function() {
          _this.getnewestList(id)
        }, 5000)
      },
      async getnewestList(id) {
        const res = await customerAttachment({ csmCode: this.temp.csmCode })
        this.imgdata = [].concat(res.data.cardItems)
        const list = this.imgdata.filter(item => item.csmId === id)
        if (list && list.length) {
          if (list[0].picInfos && list[0].picInfos.length > this.curSize) {
            // 轮询结束
            clearInterval(this.checkInterval)
            this.getattachmentlist(1)
          }
        }
      },
      reset() {
        this.query.cardType = ''
        this.query.cardNo = ''
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  & /deep/ .el-form-item {
    width: 33%;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
.info-box {
  width: 100%;
  padding: 20px;
  margin-top: 20px;
  border: 1px solid #eee;
  .info-item {
    margin-bottom: 10px;
    border-bottom: 1px dashed #eee;
    .flex {
      display: flex;
      justify-content: space-between;
      .titlename {
        margin-bottom: 10px;
        font-weight: 600;
      }
      .card-no {
        font-weight: 300;
      }
    }
    .img-box {
      display: flex;
      justify-content: space-around;
      margin-top: 10px;
      margin-bottom: 10px;
    }
    .img-item {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 200px;
      height: 160px;
      background: #fff;
      border: 1px solid #eee;
      border-radius: 5px;
      img {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
      .deleteimg {
        position: absolute;
        // color: red;
        top: 0;
        right: 0;
        font-size: 20px;
      }
    }
    .img-empty {
      display: flex;
      align-items: center;
      justify-content: center;
      background: #eee;
      img {
        width: 30px;
        height: 30px;
      }
    }
    .remark-part {
      margin-bottom: 10px;
    }
  }
}
</style>
